<template>
  <div class="robot-list-container">
    <!-- 顶部导航 -->
    <van-nav-bar title="新的好友" left-arrow @click-left="goBack" class="nav-bar" />

    <van-row v-if="list" style="padding:10px;overflow-y: auto;">
  <template v-for="(friend, index) in list" >
    <!-- 时间标签（在消息框外，上方） -->
    <div class="time-separator" :key="'time_' + index">
      {{ friend.createtime }}
    </div>

    <!-- 消息项 -->
    <div class="friend-item" :key="'item_' + index">
      <!-- 原有内容保持不变 -->
      <div class="header">
        <span class="name">{{ friend.isApplicant ? '您' : friend.realname }}</span>
        <span class="status">申请添加好友</span>
        <span
          class="tag"
          :class="{
            'tag-success': friend.judgment === '1',
            'tag-danger': friend.judgment === '0',
            'tag-warning': friend.judgment === '2'
          }"
        >
          {{ getStatusText(friend.judgment) }}
        </span>
      </div>

      <div class="info-row">
        <van-image
          round
          width="48px"
          height="48px"
          :src="friend.avatar"
          class="avatar"
        />
        <div class="text-info">
          <div class="realname">{{ friend.realname }}</div>
          <div class="phone">{{ friend.phone }}</div>
        </div>
      </div>

      <div class="content">{{ friend.content }}</div>

      <div v-if="!friend.isApplicant && friend.judgment === '2'" class="action-buttons">
        <van-button type="default" class="next-btn" size="small" @click="handleReject(friend)">拒绝</van-button>
        <van-button type="primary" class="next-btn" size="small" @click="handleAgree(friend)">同意</van-button>
      </div>
    </div>
  </template>
</van-row>
  </div>
</template>

<script>
import { postAction, getFileAccessHttpUrl } from "@/api";
import { Toast } from "vant";

export default {
  name: "addfriend",
  data() {
    return {
      userInfo: {},
      list: [],
    };
  },
  mounted() {
    const userInfoString = localStorage.getItem("pro__login_user_info");
    if (userInfoString) {
      const userInfo = JSON.parse(userInfoString);
      this.userInfo = userInfo.value;
    }
    this.search();
  },
  methods: {
    goBack() {
      this.$router.push({ name: "contact" });
    },
    search() {
      postAction("/sys/chat/FriendRequest/getList", {
        id: this.userInfo.id,
      }).then((res) => {
        console.log("🚀 ~ search ~ res:", res);
        if (res.code === 200) {
          this.list = res.result;
          this.list.forEach((item) => {
            item.avatar = item.avatar ? getFileAccessHttpUrl(item.avatar) : '/static/mobile/img/common/user_default.webp';
            item.createtime = this.formatChatTime(item.createtime)
          });
        } else {
          Toast.fail(res.message);
        }
      });
    },
    // 获取状态文本
    getStatusText(judgment) {
      return { "0": "已拒绝", "1": "已同意", "2": "待处理" }[judgment] || "未知";
    },
    // 同意请求
    handleAgree(friend) {
      this.handleAction(friend, "1");
    },
    // 拒绝请求
    handleReject(friend) {
      this.handleAction(friend, "0");
    },
    // 统一处理同意/拒绝
    handleAction(friend, judgment) {
      postAction("/sys/chat/FriendRequest/handle", {
        myid: this.userInfo.id,
        otherid: friend.otherid,
        judgment: judgment,
      }).then((res) => {
        if (res.code === 200) {
          Toast.success(judgment === "1" ? "已同意" : "已拒绝");
          friend.judgment = judgment; // 更新状态
        } else {
          Toast.fail(res.message);
        }
      });
    },
    // 格式化时间显示（用于聊天列表）
  formatChatTime(timestamp) {
    if (!timestamp) return '';

    // 解析时间字符串
    const date = new Date(timestamp);
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    // 获取目标时间的“日”起点
    const target = new Date(date.getFullYear(), date.getMonth(), date.getDate());

    // 判断时间差
    const diffDays = Math.floor((target - today) / (1000 * 60 * 60 * 24));

    // 格式化时间部分（小时:分钟）
    const timeStr = date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
    }).replace(/^24/, '00'); // 修复 24:00 显示问题

    // 判断显示逻辑
    if (diffDays === 0) {
      return timeStr; // 今天：只显示时间
    } else if (diffDays === -1) {
      return `昨天 ${timeStr}`; // 昨天
    } else {
      // 更早：显示 月 日 时:分
      return `${date.getMonth() + 1}月${date.getDate()}日 ${timeStr}`;
    }
  },
  },
};
</script>

<style scoped>
.robot-list-container {
  background-color: #f4f8f9;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.friend-item {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 10px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
  position: relative;
}

/* 创建时间 */
.create-time {
  font-size: 12px;
  color: #969799;
  margin-bottom: 8px;
  text-align: right;
}

/* 第一行：姓名 + 状态 + 右上角标签 */
.header {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #323233;
  font-weight: 500;
  margin-bottom: 8px;
  position: relative;
}

.header .status {
  margin-left: 6px;
  color: #969799;
  font-size: 14px;
}

.tag {
  position: absolute;
  right: -16px;
  top: -12px;
  font-size: 12px;
  padding: 10px 16px;
  border-radius: 0px 10px;
  background-color: #f0f0f0;
  color: #666;
}

.tag-success {
  background-color: #07c160;
  color: #ffffff;
}

.tag-danger {
  background-color: #fde2e2;
  color: #c66;
}

.tag-warning {
  background-color: #fdf6e9;
  color: #e6a23c;
}

/* 第二行：头像 + 文本信息 */
.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.text-info {
  margin-left: 12px;
}

.realname {
  font-size: 15px;
  color: #323233;
}

.phone {
  font-size: 13px;
  color: #969799;
  margin-top: 4px;
}

/* 第三行：验证信息 */
.content {
  font-size: 14px;
  color: #646566;
  margin-bottom: 10px;
  padding-left: 5px;
  /* 与头像对齐 */
  background: #F2F2F2;
  line-height: 30px;
}

/* 第四行：操作按钮 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  margin-top: 10px;
}

.next-btn {
  padding: 0 25px;
}

/* 时间分隔符 - 显示在消息框外部上方 */
.time-separator {
  font-size: 12px;
  color: #969799;
  text-align: center;
  margin: 16px 0 4px;
  /* 上方留白多，下方少，靠近消息框 */
  padding: 2px 10px;
  display: inline-block;
  background-color: #f4f8f9;
  border-radius: 6px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  min-width: 100px;
}
</style>